package com.example.dao;

import com.example.pojo.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ControllerAdvice;
import utils.ShareCodeUtil;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by wushuai on 17/8/31.
 */
@Repository
@ControllerAdvice
public class AccountDao extends JdbcDaoSupport {

    // 根据id查询用户
    public Account selectUser (String un, String pw) {
        String sql = "SELECT user_code, username, user_code FROM db_account WHERE username=? AND password=?";

        Account account = super.getJdbcTemplate().queryForObject(sql, new Object[]{un, pw}, new BeanPropertyRowMapper<Account>(Account.class));
        return account;
    }

    // 注册账号
    public boolean addAccount (final Account account) {
        String sql = "INSERT INTO db_account(username, password, user_code) VALUE(?, ?, ?)";

        int success = super.getJdbcTemplate().update(sql,
                new PreparedStatementSetter() {
                    public void setValues(java.sql.PreparedStatement preparedStatement) throws SQLException {
                        preparedStatement.setString(1, account.getUserName());
                        preparedStatement.setString(2, account.getPassword());
                        preparedStatement.setString(3, ShareCodeUtil.toSerialCode(System.currentTimeMillis()));
                    }
                }
        );
        return success >= 1;
    }

    public List<Account> findAll () {
        String sql = "SELECT * FROM db_account";

        List<Account> accounts = super.getJdbcTemplate().query(sql, new BeanPropertyRowMapper<Account>(Account.class));
        return accounts;
    }

    @Resource
    public void setJb(JdbcTemplate jb) {
        super.setJdbcTemplate(jb);
    }
}
